<template>
  <div class="thMap" :style="{ width, height }">
    <div id="report-maps"></div>
    <div class="map-cancle" @click="mapCancle">取消</div>
    <div
      class="map-confirm"
      @click="mapConfirm"
    >
      确定
    </div>
    <div class="map-bottom-popup">
      <div class="map-popup-line" @click="mapPopupLine"></div>
      <div class="map-search">
        <input type="text" id="tip" placeholder="请输入街道名、建筑名等" >
        <i class="icon" @click="search"></i>
      </div>
      <div class="map-list">
        <div class="map-list-item" v-for="(item, index) in mapList" :key="index" @click="touchItem(item.label)">
          {{ item.label }}
        </div>
      </div>
    </div>

    <div class="map-geolocation" @click="Geolocation"></div>

  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'


const props = defineProps({
  width: {
    type: String,
    default: '300px'
  },
  height: {
    type: String,
    default: '500px'
  }
})
const thMap = ref(null)
const mapPopupTop = ref(50)
const marker = ref(null)

const mapList = ref([
  {label: "北京市朝阳区", value: "1"},
  {label: "北京市海淀区", value: "2"},
  {label: "北京市昌平区", value: "3"},
  {label: "北京市大兴区", value: "4"},  
  {label: "北京市顺义区", value: "5"},  
  {label: "北京市怀柔区", value: "6"},  
])    


const mapInit = () => {
    // 创建地图实例
  thMap.value = new BMapGL.Map('report-maps', {
    coordsType: 5 // coordsType指定输入输出的坐标类型，3为gcj02坐标，5为bd0ll坐标，默认为5。
  })
  // 初始化地图, 设置中心点坐标和地图级别
  const point = new BMapGL.Point(116.404, 39.915);
  thMap.value?.centerAndZoom(point, 12);
  thMap.value?.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
  addMarker(116.404, 39.915) // 增加地图点
  window.hideGlobalLoading()


  // 点击地图事件
  thMap.value?.addEventListener('click', function (e: any) {
    mapIsClick(e)
  })

}

// 添加mark
const addMarker = (lng: any, lat: any) => {
  if (marker.value) {
    thMap.value?.removeOverlay(marker.value);
  }
  // 百度
  var point = new BMapGL.Point(lng, lat);
  thMap.value?.centerAndZoom(point, 17);
  const size = new BMapGL.Size(34.5, 37.5)
  var myIcon = new BMapGL.Icon(
    "https://appservice.epicc.com.cn/autodata/web/imgs/charge.png",
    size,
    {anchor: new BMapGL.Size(size.width / 2, size.height)}
  );
  // marker.value.setIcon(myIcon)
  marker.value = new BMapGL.Marker(point, {
    icon: myIcon
  }); // 创建标注
  thMap.value?.addOverlay(marker.value)
  // thMap.value?.setViewport()
}


const mapIsClick = (e: any) => {
  console.log('log', e.latlng)
  getAddress(e.latlng)
}

const getAddress = (latlng: any) => {
  // 解析坐标点
  let myGeo = new window.BMapGL.Geocoder()
  myGeo.getLocation(latlng, function (res: any) {
    console.log(res);
    console.log(res.address)
    
  // 地图打开信息窗口
  var windowPoint = new window.BMapGL.Point(res.point.lng,res.point.lat);
  console.log(windowPoint);
  var infoWindow = new window.BMapGL.InfoWindow(res.address, {
    width: 0,
    height: 0,
    title: "地址名称",
  });
  thMap.value?.openInfoWindow(infoWindow, windowPoint)
  })
}

const mapCancle = () => {
  alert('取消了')
}

const mapConfirm = () => {
  play()
}

// 设置弹出框距离顶部高度
const mapPopupLine = () => {
  // return
  var mapPopup = document.querySelector(".map-bottom-popup");
  console.log("mapPopupTop.value", mapPopupTop.value);
  mapPopup.style.top = mapPopupTop.value + "px";
}

// 拖拽
const dragger = () => {
  // map-search
  var mapPopup = document.querySelector(".map-bottom-popup");
  var dragEl = document.querySelector(".map-search");
  var BODY_HEIGHT = document.documentElement.clientHeight;
  var HEIGHT;
  var touches;
  var TOP;
  dragEl.addEventListener(
    "touchstart",
    function(e) {
      touches = e.touches[0];
      HEIGHT = touches.clientY - mapPopup.offsetTop;
      document.body.style.overflow = "hidden";
      document.body.addEventListener(
        "touchmove",
        function(e) {
          e.preventDefault();
        },
        false
      );
    },
    { passive: false }
  );
  dragEl.addEventListener(
    "touchmove",
    function(e) {
      touches = e.touches[0];
      TOP = touches.clientY - HEIGHT;
      var DRAGEL_HEIGHT = mapPopup.offsetHeight;
      if (TOP <= BODY_HEIGHT - mapPopup.clientHeight) {
        TOP = BODY_HEIGHT - mapPopup.clientHeight;
      } else if (TOP >= BODY_HEIGHT - 80) {
        TOP = BODY_HEIGHT - 80;
      }
      mapPopup.style.top = TOP + "px";
    },
    false
  );
  dragEl.addEventListener(
    "touchend",
    function(e) {
      document.body.style.overflow = "scroll";
      document.body.removeEventListener(
        "touchmove",
        function(e) {
          e.preventDefault();
        },
        false
      );
    },
    false
  );
}

const touchItem = (label) => { 
  demo(label)
}

const search = () => {
  alert('搜索') 
  addMarker(126.67968, 45.72383);
  getAddress(new BMapGL.Point(126.67968, 45.72383))
}

 // 定位SDK辅助定位
 const GetPositionByBaduSDK = () => {
    return new Promise((resolve, reject) => {
      window.showGlobalLoading()
      var geolocation = new BMapGL.Geolocation();
        // 开启SDK辅助定位
        geolocation.enableSDKLocation();
        geolocation.getCurrentPosition(function(r: any) {
          console.log(r);
            if(this.getStatus() == BMAP_STATUS_SUCCESS) {
              let {lng, lat} = r.point
              let position = {
                  lng: lng,
                  lat: lat,
              }
              window.hideGlobalLoading()
              resolve(position)
            } else {
              let position = {
                  lng: '',
                  lat: '',
              }
              window.hideGlobalLoading()
              ElMessage.warning('获取失败')
              reject(position)
            }
        });
    })
}

const Geolocation = () => {
  alert('定位当前')
  GetPositionByBaduSDK()
  .then(res => {
    const { lng, lat } = res
    // 添加mark
    addMarker(lng, lat)

    // const mk = new BMapGL.Marker(res)
    // thMap.value?.addOverlay(mk)
    // thMap.value?.panTo(res)

    // getAddress(new BMapGL.Point(lng, lat))
  })
  .catch(err => {
    console.log(err, "44");
  });



}

const demo = (label: string) => {
  var myGeo = new BMapGL.Geocoder();
  let add = label
    myGeo.getPoint(
    add,
    function (point) {
      console.log(point);
      let startPoint = point;
      if (point) {
        thMap.value?.centerAndZoom(point, 20);
        //   地图倾斜角度
        thMap.value?.setTilt(50);
        thMap.value?.addOverlay(new BMapGL.Marker(point, { title: add }));
      } else {
        alert("您选择地址没有解析到结果!");
      }
  })
}

const play = () => {
  var addr = "立水桥";
      //   创建地址解析实例
      var myGeo = new BMapGL.Geocoder();
      myGeo.getPoint(
        addr,
        function (point) {
          console.log(point);
          let startPoint = point;
          if (point) {
            thMap.value?.centerAndZoom(point, 20);
            //   地图倾斜角度
            thMap.value?.setTilt(50);
            thMap.value?.addOverlay(new BMapGL.Marker(point, { title: addr }));
          } else {
            alert("您选择地址没有解析到结果!");
          }
 
          // 查找终点位置体育西路
          var endAddr = "朝阳区奥体中心地铁a口";
          myGeo.getPoint(
            endAddr,
            function (point) {
              console.log(point);
              if (point) {
                let endPoint = point;
                // 设置驾车路线
                var driving = new BMapGL.DrivingRoute(thMap.value, {
                  renderOptions: {
                    map: thMap.value,
                    autoViewport: true,
                  },
                  onSearchComplete: function (results) {
                    console.log(results);
 
                    // 获取第一条路线
                    var plan = results.getPlan(0);
                    console.log(plan);
                    console.log("路程：" + plan.getDistance());
                    console.log("耗时：" + plan.getDuration());
                  },
                });
                driving.search(startPoint, endPoint);
              }
            },
            "北京市"
          );
        },
        "北京市"
      )
}

onMounted(() => {
  window.showGlobalLoading()
  dragger();
  mapPopupTop.value = document.querySelector(
    '.map-bottom-popup'
  ).offsetTop;
  mapInit()
})


</script>

<style lang="scss" scoped>

.thMap {
  // width: 300px;
  // height: 500px;
  border: 1px solid #ddd;
  position: relative;
  z-index: 10;
  overflow: hidden;
  box-sizing:border-box;
  #report-maps {
    width: 100%;
    height: 100%;
  }
  .map-cancle {
    position: absolute;
    top: 13px;
    left: 16px;
    font-size: 16px;
    color: #333333;
    font-weight: bold;
    border-radius: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    z-index: 20;
  }
  .map-confirm {
    width: 60px;
    height: 32px;
    position: absolute;
    top: 6px;
    right: 16px;
    background-image: linear-gradient(135deg, #f3706a 0%, #ff4b38 100%);
    box-shadow: 0px 0px 20px 0px rgba(89, 56, 56, 0.1);
    border-radius: 16px;
    font-size: 14px;
    color: #ffffff;
    font-weight: bold;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    z-index: 20;
  }

  .map-bottom-popup {
    box-shadow:0 0 5px 2px rgba(0,0,0,0.1);
    position: absolute;
    bottom: 0;
    background: #ffffff;
    width: 100%;
    height: 200px;
    border-top-left-radius: 12px;
    border-top-right-radius: 12px;
    cursor: pointer;
    overflow: hidden;
    z-index: 20;
    .map-popup-line {
      position: absolute;
      height: 4px;
      width: 60px;
      background: #d5d5d5;
      border-radius: 100px;
      top: 8px;
      left: 50%;
      transform: translateX(-50%);
      display: flex;
      flex-direction: column;
    }
    .map-search {
      position: absolute;
      // margin-top: 5px;
      top: 5px;
      width: 100%;
      padding: 5px;
      box-sizing:border-box;
      input {
        width: 100%;
        height: 25px;
        border: 1px solid #eee;
        border-radius: 10px;
        // box-shadow:0 0 5px 2px rgba(0,0,0,0.1);
        padding: 0 5px;
        box-sizing:border-box;
      }
      ::-webkit-input-placeholder {
        color: #666;
        font-size: 12px;
        text-align: center;
      }
      .icon{
        display: inline-block;
        height: 20px;
        width: 20px;
        background-image: url(./img/small.svg); /*这里放置图标的绝对路径*/
        background-repeat: no-repeat;
        position: absolute;
        top: 14%;
        right: 10px;
        z-index: 2;
      }
    }
    .map-list {
      position: absolute;
      left: 0;
      top: 40px;
      // flex: 1;
      width: 100%;
      display: flex;
      flex-direction: column;
      font-size: 14px;
      color: #666;
      overflow-y: scroll;
      .map-list-item {
        margin-top: 3px;
        padding: 0 8px;
        height: 35px;
        display: flex;
        justify-content: start;
        align-items: center;
        border: 1px solid #eee;
        cursor: pointer;
      }
      :hover {
        background-color: #eee;
      }
    }
  }
  .map-geolocation {
    z-index: 99;
    position: absolute;
    bottom: 230px;
    right: 16px;
    height: 40px;
    width: 40px;
    box-shadow: 0 0 5px silver;
    cursor: pointer;
    background-image: url("./img/th_location.png");
    background-size: 80px;
    background-repeat: no-repeat;
    background-position: 50%;
  }
}

</style>